package zouran.login.controller;


import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import zouran.login.emailUtil.SendEmail;
import zouran.login.entity.Captcha;
import zouran.login.entity.UserInfo;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 登录验证
 * @author zouran
 * createDate：2023/5/13  15:14
 */
@RestController
@RequestMapping("/logon")
public class logonController {
    private final SendEmail sendEmail;
    //验证码最小值
    private static final Integer minCaptcha =100000;
    //验证码最大值
    private static final Integer maxCaptcha =1000000;
    //验证码发送的时间差
    private static final Integer interval=1;
    //验证码有效期
    private static final Integer validity=5;
    //存放所有验证码
    private final Map<String, Captcha> captchaMap =new HashMap<>();

    public logonController(SendEmail sendEmail) {
        this.sendEmail = sendEmail;
    }

    /**
     * 获取验证码
     * @param email 用户唯一账号识别（手机号码或者邮箱等）
     */
    @RequestMapping("/captcha")
    public String sendCaptcha(@RequestParam("email") String email){
        if(captchaMap.containsKey(email)&& captchaMap.get(email).isValid())
            return "验证码请求过于频繁!";
        Random random=new Random();
        Integer value=random.nextInt(maxCaptcha)%(maxCaptcha - minCaptcha)+ minCaptcha;
        //发送邮箱
        if(!sendEmail.send(email,sendEmail.logonContent(String.valueOf(value)), SendEmail.TITLE_LOGON))
            return "验证码发送失败!";
        Captcha captcha=new Captcha(value,true);
        captchaMap.put(email,captcha);
        ScheduledExecutorService schedule= Executors.newScheduledThreadPool(1);
        schedule.schedule(() -> captchaMap.get(email).setValid(false),interval, TimeUnit.MINUTES);
        schedule.schedule(()->{
            captchaMap.remove(email);
        },validity,TimeUnit.MINUTES);
        System.out.println(captcha.getValue());
        return "发送成功";
    }
    /**
     * 检验验证码
     * @param captcha 验证码
     * @param userInfo 用户的信息类集合,使用对象方便结合validation进行入参检验
     */
    @RequestMapping("/cheekCaptcha")
    public String cheekCaptcha(@RequestParam("captcha") String captcha,@RequestBody UserInfo userInfo){
         if(captchaMap.containsKey(userInfo.getEmail())){
             if (Objects.equals(String.valueOf(captchaMap.get(userInfo.getEmail()).getValue()), captcha)){
                 /*
                  执行注册成功后操作
                  */
                 sendEmail.send(userInfo.getEmail(),sendEmail.loginSuccessContent(),SendEmail.TITLE_LOGON_SUCCESS);
                 return "logon success!";
             }
             else {
                 return "验证码错误!";
             }
         }else {
             return "验证码过期!";
         }
    }
}
